import requestApi from "@/utils/service"
export interface pageObjData {
  pageSize: number
  pageNum: number
}

import { ref, reactive, Ref } from "vue"

export function useTableHook() {
  let cachePage: pageObjData = reactive({
    pageSize: 10,
    pageNum: 1
  })
  const loading = ref<boolean>(false)
  const setLoad = (val: boolean) => {
    loading.value = val
  }

  let cacheData: any = null
  const tableData = ref([])
  const total = ref(0)

  const search = async (api?: string, pageObj?: pageObjData, data?: any) => {
    if (!data) {
      data = cacheData
    }
    if (!pageObj) {
      pageObj = {
        pageSize: 10,
        pageNum: 1
      }
    }
    cacheData = data
    cachePage = pageObj
    const params = {
      ...data,
      ...pageObj
    }
    loading.value = true
    try {
      const res: any = await requestApi.get({
        url: api,
        params
      })
      loading.value = false
      tableData.value = res.list || res
      total.value = res.total
      // 切换表格分页时将滚动条滚动到顶部
      const tableDom = document.getElementsByClassName("el-table__body-wrapper")
      for (let i = 0; i < tableDom.length; i++) {
        tableDom[i].scrollTo(0, 0)
      }
      return await Promise.resolve(res)
    } catch {
      loading.value = false
      tableData.value = []
      total.value = 0
    }
  }
  return { search, tableData, total, cachePage, loading, setLoad }
}
